<?php

namespace app\admin\service;

use app\admin\model\Storesettlement;
use app\admin\model\Usersettlement;
use app\common\model\User;
use app\common\model\Userstore;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class Pay
{
    private $orderNo;
    private $payObj;
    private $userId;

    function __construct($param)
    {
        $this->orderNo = $param['orderNo'];
        $this->payObj = $param['type'];
    }

    /**
     * 商户向用户打款
     * @return \think\response\Json
     */
    public function shanghuPay(){
        if($this->payObj == 1){
            $settlement = Usersettlement::where('orderNo',$this->orderNo)->find();
        }else{
            $settlement = Storesettlement::where('orderNo',$this->orderNo)->find();
        }
        try{
            $this->checkComOrder($settlement);
            $this->getUserId($settlement,$this->payObj);
        }catch (Exception $ex){
            return show(config('status.ERROR_STATUS'),$ex->msg,$ex->msg);
        }
        $res = $this->GoshanghuPay($settlement->amount,$settlement->orderNo,$this->payObj);

        if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
            return show(config('status.SUCCESS_STATUS'),'ok','支付成功');
        }else{
            if(!empty($res['err_code']) && $res['err_code'] == 'NOTENOUGH'){
                return show(config('status.ERROR_STATUS'),'支付失败','商户余额不足，请去微信商户平台充值');
            }elseif (!empty($res['err_code']) && $res['err_code'] == 'AMOUNT_LIMIT'){
                return show(config('status.ERROR_STATUS'),'支付失败','付款金额超限');
            }else{
                return show(config('status.ERROR_STATUS'),'支付失败','支付失败');
            }

        }

    }

    private function GoshanghuPay($amount,$OrderNo,$payObj){
        $openid = User::getopenId($this->userId);
        $wxOrderData = new \WxPayTransfers();
        $wxOrderData->SetPartner_trade_no($OrderNo);
        $wxOrderData->SetOpenid($openid);
        $wxOrderData->SetAmount($amount);
        $wxOrderData->SetDesc('佣金提现');
        $wxOrderData->SetCheck_name('NO_CHECK');

        return $this->DoTransfers($wxOrderData,$payObj);
    }


    private function DoTransfers($wxOrderData,$payObj){
//        <xml>
//        <return_code><![CDATA[SUCCESS]]></return_code>
//        <return_msg><![CDATA[]]></return_msg>
//        <mch_appid><![CDATA[wxec38b8ff840bd989]]></mch_appid>
//        <mchid><![CDATA[10013274]]></mchid>
//        <device_info><![CDATA[]]></device_info>
//        <nonce_str><![CDATA[lxuDzMnRjpcXzxLx0q]]></nonce_str>
//        <result_code><![CDATA[SUCCESS]]></result_code>
//        <partner_trade_no><![CDATA[10013574201505191526582441]]></partner_trade_no>
//        <payment_no><![CDATA[1000018301201505190181489473]]></payment_no>
//        <payment_time><![CDATA[2015-05-19 15：26：59]]></payment_time>
//        </xml>

        $wxOrder = \WxPayApi::transfers($wxOrderData);
        if($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS'){
            Log::record($wxOrder,'error');
            Log::record('商户向用户打款失败','error');
        }else{
            //打款成功后处理逻辑
            $this->transfersSuccess($wxOrder,$payObj);
        }
        return $wxOrder;
    }

    private function transfersSuccess($wxOrder,$payObj){
        Db::startTrans();
        try
        {
            if($payObj == 1){
                $settlement = Usersettlement::where('orderNo',$wxOrder['partner_trade_no'])->find();
            }else{
                $settlement = Storesettlement::where('orderNo',$wxOrder['partner_trade_no'])->find();
            }
            $settlement->status = 1;
            $settlement->settleTime = $wxOrder['payment_time'];
            $settlement->tradeNo = $wxOrder['payment_no'];
            $settlement->save();
            Db::commit();
        }catch (Exception $ex){
            Db::rollback();
            Log::record($ex);
        }
    }

    private function getUserId($model,$payObj){
        if($payObj ==1){
            $userId =  $model->userId;
        }else{
           $Userstore =  Userstore::where('storeId',$model->storeId)->find();
           if($Userstore){
               $userId = $Userstore->userId;
           }else{
               throw new ParameterException([
                   'msg' => '提现用户异常'
               ]);
           }
        }
        $this->userId = $userId;
    }

    //对用户或店铺提现订进行检测
    private function checkComOrder($model){
        if($model){
            if($model->status !=2 && $model->status != 0){
                throw new ParameterException([
                    'msg' => '该订单可能已经支付过了'
                ]);
            }
        }else{
            throw new ParameterException([
                'msg' => '当前提现订单不存在'
            ]);
        }
    }
}